package com.yvan.leto;

import com.yvan.Conv;
import com.yvan.http.HttpSession;
import com.yvan.http.YvanCookieJar;
import com.yvan.platform.JsonWapper;
import com.yvan.platform.StringUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.Response;

@Slf4j
public class ConfigApi {

    private static final String FMT_CURL_OK = "${server}/ok";
    private static final String FMT_CURL_ZK = "${server}/leto/api/zk";
    private static final String FMT_CURL_PROJECT = "${server}/leto/api/${env}/${project}/${segment}";

    private final HttpSession session = new HttpSession(new YvanCookieJar());
    private final String server;

    public ConfigApi(String server) {
        this.server = server;
    }

    public ZkProperties getZkProperty() {
        final String zkAddress = StringUtils.format(FMT_CURL_ZK)
                .set("server", server)
                .build();
        JsonWapper jwZk = session.curl().get(zkAddress).executeJson();
        return jwZk.asObject(ZkProperties.class);
    }

    public String getSegmentContent(String env, String project, String segment) {

        final String address = StringUtils.format(FMT_CURL_PROJECT)
                .set("server", server)
                .set("env", env)
                .set("project", project)
                .set("segment", segment)
                .build();
        return session.curl().get(address).executeText();
    }

    public Boolean isConfigServerOk(){
        try{
            final String address = StringUtils.format(FMT_CURL_OK)
                    .set("server", server)
                    .build();
            Response response = session.curl().get(address).execute();
            return response.isSuccessful();
        }
        catch (Exception ex){
            log.error("config server is not ok! will load config files in native cache",ex);
        }
        return false;
    }
}
